<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\lib\Ali;
use app\common\model\Poem as PoemModel;

class Poem extends AdminBase
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        $list = PoemModel::order('id asc')->paginate(['query' => $this->request->param()]);
        return view('', \compact('list'));
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $form = $this->form();
            if (!\is_array($form)) {
                $this->error($form);
            }
            $result = PoemModel::create($form);
            if ($result) {
                $result->createQuestion();
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        }
        return view('form');
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $data = PoemModel::where('id', $id)->find();
        if ($this->request->isPost()) {
            $form = $this->form();
            if (!\is_array($form)) {
                $this->error($form);
            }
            $result = PoemModel::update($form);
            if ($result) {
                @\unlink(\public_path() . $data['record']);
                $data->createQuestion();
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        }
        return view('form', \compact('data'));
    }

    private function form()
    {
        $form = $this->request->param();
        $ali = Ali::getClint();
        
        $res = $ali->tts("{$form['title']}，{$form['author']}，{$form['content']}");
        if (!$res) {
            return $ali->error;
        }
        $form['record'] = $ali->filePath;
        return $form;
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $this->error('禁止删除');

        return;
        $result = PoemModel::destroy($id);
        if ($result) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }
}
